package OOPAndMultiThreadArchiveManager.Server.Controllers;

import OOPAndMultiThreadArchiveManager.Server.Models.ApiReceive;
import OOPAndMultiThreadArchiveManager.Server.Models.ApiResponse;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.net.Socket;

public class MainController extends Thread {
    private Socket socket;
    private final static ObjectMapper objectMapper = new ObjectMapper();

    public MainController(Socket socket) throws IOException {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            var inputStream = new DataInputStream(socket.getInputStream());
            var byteArrayOutputStream = new ByteArrayOutputStream();
            var bytes = new byte[2048];
            var n = 0;
            while ((n = inputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, n);
            }
            var stringInputStream = byteArrayOutputStream.toString();
            socket.shutdownInput();

            ApiReceive receive = objectMapper.readerFor(ApiReceive.class).readValue(stringInputStream);
            byteArrayOutputStream.close();
            var userController = new UserController(receive);
            var response = userController.actionResult();

            var outputStream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
            outputStream.writeUTF(objectMapper.writeValueAsString(response));
            outputStream.flush();
            outputStream.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}